//
//  SettingViewController.m
//  WisdomZhuHai
//
//  Created by yewei on 14/10/30.
//  Copyright (c) 2014年 wyd. All rights reserved.
//
//  Modified by Ryan on 14/12/03.

#import "SettingViewController.h"
#import "AboutViewController.h"
#import "FeedbackViewController.h"
#import "AppShareView.h"
#import "AppDelegate.h"
#import "PersonPhoneViewController.h"
#import "PersonViewController.h"
#import "TransforController.h"

#define LOGINSTATUS @"loginStatus.plst"

@interface SettingViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic,strong) NSArray *texts;
@property (nonatomic,strong) NSArray *icons;
@property (nonatomic,strong) NSString *appEvaluateUrl;
@property (nonatomic,strong) NSString *updateUrl;
@property (nonatomic, strong) NSString *string_version;
@property (nonatomic, strong) UITableViewCell *cell_mobileBinding;


@end

@implementation SettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.texts = @[@"应用分享",@"评价我们",@"关于我们",@"版本更新",@"清除缓存"];
//    self.icons = @[@"sidebar/share.png",@"sidebar/appraise.png",@"sidebar/about.png",@"sidebar/update.png",@"sidebar/Eliminate.png"];
    self.texts = @[@"应用分享",@"评价我们",@"关于我们",@"检查更新"];
    self.icons = @[@"sidebar/share.png",@"sidebar/appraise.png",@"sidebar/about.png",@"sidebar/update.png"];
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.tableView.bounds.size.width, 0.1)];
    self.tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,self.tableView.bounds.size.width, 0)];
    self.tableView.backgroundColor = [UIColor colorWithRed:235/250.0 green:235/250.0 blue:235/250.0 alpha:1];
    self.title = @"设置";
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
//    self.tableView.scrollEnabled = NO;
    self.tableView.frame = CGRectMake(0, 65, 320, 503);
    [self.view setFrame:CGRectMake(0, -65, 320, 613)];
//    self.view.backgroundColor = [UIColor whiteColor];
//    UIView *view_navigationbar = [TransforController shardeInstanceOfNavigationBarAndStatusBarCoverViewWithY:-65];
//    [self.view addSubview:view_navigationbar];
    [[ProtocolManager shareInstance] getUpdateInfo:self selector:@selector(didFinishGetUpdateNew:)];
    
}

-(void)didFinishGetAppEvaluateUrl:(NSDictionary *)dic
{
    if(dic == nil)
    {
        NSLog(@"SettingViewController didFinishGetAppEvaluateUrl dic is nil");
        return;
    }
    self.appEvaluateUrl = [Common valueForKey:P_URL dic:dic];
    [[UIApplication sharedApplication] openURL:[Common getUrlByString:self.appEvaluateUrl]];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (section) {
        case 2:
            return 1;
            break;
        case 0:
            return [self.texts count];
        case 3:
            return 1;
        case 1:
            return 1;
        default:
            return 0;
            break;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    switch (indexPath.section) {
//        case 0:
//        case 1:
//            return 45;
//            break;
//        case 2:
//            return 50;
//        default:
//            break;
//    }
    return 45;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    switch (section) {
        case 1:
            return @"联系我们";
        case 3:
            if([ProtocolManager shareInstance].mobile == nil || [ProtocolManager shareInstance].mobile.length < 11){
                return @"尚未未绑定手机";
            }else{
                return @"已绑定手机";
            }
        default:
            return @"";
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = nil;
    switch (indexPath.section) {
        case 3:
            cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if(cell == nil){
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
                if([ProtocolManager shareInstance].mobile == nil || [ProtocolManager shareInstance].mobile.length < 11){
                    cell.textLabel.text = @"点击绑定";
                }else{
                    cell.textLabel.text = [ProtocolManager shareInstance].mobile;
                    cell.detailTextLabel.text = @"更换绑定";
                }
                self.cell_mobileBinding = cell;
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            }
            break;
        case 0:
            cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if(cell == nil)
            {
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
            }
            // Configure the cell...
            cell.textLabel.text = [self.texts objectAtIndex:indexPath.row];
            cell.imageView.image = [UIImage imageNamed:[self.icons objectAtIndex:indexPath.row]];
            if(indexPath.row == 3){
                cell.detailTextLabel.text = self.string_version;
            }
            break;
        case 1:
            cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if(cell == nil){
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
                cell.textLabel.text = @"客服电话";
                cell.detailTextLabel.text = [ProtocolManager shareInstance].telephone;
            }
            break;
        case 2:
            cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if(cell == nil){
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
                UILabel *lb_logout = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 320, 45)];
                lb_logout.textAlignment = UITextAlignmentCenter;
//                lb_logout.textColor = [UIColor redColor];
                lb_logout.font = [UIFont fontWithName:@"Arial" size:16.0];
                lb_logout.text = @"清除缓存";
                [cell addSubview:lb_logout];
            }
        default:
            break;
    }
//    UIView *v = [[UIView alloc]init];
//    v.backgroundColor = [UIColor clearColor];
//    cell.backgroundView = v;
//    cell.textLabel.backgroundColor = [UIColor clearColor];
//    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    switch (indexPath.section) {
        case 1:
            [self dialPhoneNumber];
            break;
        case 0:
            switch (indexPath.row){
            case 0:{
                //应用分享
                AppShareView *shareView = [[AppShareView alloc] initWithFrame:[UIScreen mainScreen].bounds];
                //            [[UIApplication sharedApplication].keyWindow addSubview:shareView];
                shareView.string_share = @"欢迎使用OK珠海,  享受“食、住、行、游、娱、购”移动端的“一站式”服务, 下载请戳 http://m.okhaolvxing.com/";
                [[UIApplication sharedApplication].keyWindow.rootViewController.view addSubview:shareView];
            }
                break;
            case 1:{
                //评价我们
                [[ProtocolManager shareInstance] getAppEvaluateUrl:self selector:@selector(didFinishGetAppEvaluateUrl:)];
                
            }
                break;
            case 2:{
                //关于我们
                AboutViewController *about = [[AboutViewController alloc] initWithNibName:@"AboutViewController" bundle:nil];
                [self.navigationCtrl pushViewController:about animated:YES];
                break;
            }
            case 3:{
                //检查更新
                [[ProtocolManager shareInstance] getUpdateInfo:self selector:@selector(didFinishGetUpdateInfo:)];
            }
                    break;
                break;
            default:
                break;
        }

            break;
        case 2:
            dispatch_async(
                           dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
                           , ^{
                               NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
                               
                               NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
                               NSLog(@"files :%d",[files count]);
                               for (NSString *p in files) {
                                   NSError *error;
                                   NSString *path = [cachPath stringByAppendingPathComponent:p];
                                   if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
                                       [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
                                   }
                               }
                               [self performSelectorOnMainThread:@selector(clearCacheSuccess) withObject:nil waitUntilDone:YES];});
            break;
        case 3:
            [self logoutAction];
            break;
        default:
            break;
    }
}

-(void)didFinishGetUpdateInfo:(NSDictionary *)dic
{
    if(dic == nil)
    {
        NSLog(@"SpecialMessageViewController didFinishGetUpdateInfo dic is nil");
        return;
    }
    NSString *version = [Common valueForKey:P_NUM dic:dic];
    self.updateUrl = [Common valueForKey:P_URL dic:dic];
    if([Common isNewAppVersion:version])
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"有新的版本可供下载，是否立即更新" delegate:self cancelButtonTitle:@"否" otherButtonTitles:@"是", nil];
        [alert show];
        
    }
    else
    {
        [[Common shareInstance] showAlertViewWithTitle:nil text:@"已是最新版本！" dismissTime:1.0];
    }
}

-(void)didFinishGetUpdateNew:(NSDictionary *)dic
{
    if(dic == nil)
    {
        NSLog(@"SpecialMessageViewController didFinishGetUpdateInfo dic is nil");
        self.string_version = @"更新暂不可用";
        return;
    }
    NSString *version = [Common valueForKey:P_NUM dic:dic];
    self.updateUrl = [Common valueForKey:P_URL dic:dic];
    if([Common isNewAppVersion:version])
    {
        self.string_version = @"有新版本等待更新";
        
    }
    else
    {
        self.string_version =  @"已是最新版本";
    }
    [self.tableView reloadData];
}

- (void) dialPhoneNumber
{
    NSLog(@"%s || dial phone pressed.", __FUNCTION__);
    UIWebView *phoneCallWebView = [[UIWebView alloc] initWithFrame:CGRectZero];
    NSURL *phoneURL = [NSURL URLWithString:[NSString stringWithFormat:@"tel:%@",[ProtocolManager shareInstance].telephone]];
    if (!phoneCallWebView) {
        phoneCallWebView = [[UIWebView alloc] initWithFrame:CGRectZero];
    }
    [phoneCallWebView loadRequest:[NSURLRequest requestWithURL:phoneURL]];
}

-(void)changePhoneAfterVerifying:(NSString *)phoneNumber{
    self.cell_mobileBinding.textLabel.text = phoneNumber;
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(alertView.tag == 100001){
        if(buttonIndex == 1){
            NSLog(@"Log out.");
            //[self.delegate doLogOutWithConfirm];
//            [[ProtocolManager shareInstance]logout:self selector:@selector(getLogoutFinished:)];
        }
    }else{
        if(buttonIndex == 1)
        {
            [[UIApplication sharedApplication] openURL:[Common getUrlByString:self.updateUrl]];
        }
    }
}



//- (void)gotoPhoneBindingViewController{
//    PersonPhoneViewController *personPhoneController = [[PersonPhoneViewController alloc]init];
//    NSLog(@"PhoneBind jump");
//    personPhoneController.delegate = self;
//    [self.navigationCtrl pushViewController:personPhoneController animated:YES];
////    [self presentViewController:personPhoneController animated:YES completion:nil];
//}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)logoutAction{
    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"确认退出?" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"退出", nil];
    alert.alertViewStyle=UIAlertViewStyleDefault;
    alert.tag = 100001;
    [alert show]; //显示窗口
}

- (void)getLogoutFinished:(NSDictionary *)dic{
    if(dic == nil){
        [[Common shareInstance] showAlertViewWithTitle:nil text:@"连接服务器失败" dismissTime:0.8];
        return;
    }
    ThirdViewController *temp_thirdView = [TransforController sharedInstanceOfThirdViewController];
    [temp_thirdView changeStatusAfterLogin:0];
    [[Common shareInstance] showAlertViewWithTitle:nil text:@"退出成功" dismissTime:0.8];
    [ProtocolManager shareInstance].sid = nil;
    [ProtocolManager shareInstance].userId = -1;
    [ProtocolManager shareInstance].loginName = nil;
    [ProtocolManager shareInstance].mobile = nil;
    [ProtocolManager shareInstance].username = nil;
    NSMutableDictionary *savingDic = [NSMutableDictionary dictionary];
    [savingDic setValue:@"0000" forKey:@"LoginStatus"];
    [savingDic writeToFile:[FileManager getFullDocumentPath:LOGINSTATUS]atomically:YES];
    [self.navigationController popToRootViewControllerAnimated:YES];
    
}

-(void)clearCacheSuccess
{
    NSLog(@"%s || 缓存清理成功", __FUNCTION__);
    [[Common shareInstance] showAlertViewWithTitle:nil text:@"缓存清理完毕" dismissTime:0.8];
}

@end
